package com.auxgroup.hr.front.commons.utils;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @tags 公共线程池配置
 * @author penghui
 * @createDate 2017年10月23日
 */
public class ThreadPoolUtil {

	/**
	 * 修改线程工厂 增加每个线程池的线程名称
	 * @author penghui
	 * @date 2017年10月27日
	 */
	private static class NamedThreadFactory implements ThreadFactory {

		private static AtomicInteger threadNumber = new AtomicInteger(1);
		private final String namePrefix;

		public NamedThreadFactory(String namePrefix) {
			this.namePrefix = namePrefix;
		}
        @Override
		public Thread newThread(Runnable runnable) {
			return new Thread(runnable, namePrefix + " thread-" + threadNumber.getAndIncrement());
		}

	}
	
	
	/**
	 * 获取一个线程池
	 * @param maxPoolSize
	 * @param keepAliveTime
	 * @return
	 */
	public static ExecutorService getExecutor(int corePoolSize, int maxPoolSize,long keepAliveTime,String threadName){
		return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>(), new NamedThreadFactory(threadName));
	}
		
}
